package main

import (
	//"../common"
	//"fmt"
	//"github.com/coreos/etcd/clientv3"
	//"github.com/coreos/etcd/mvcc/mvccpb"
	//"golang.org/x/net/context"
	"sync"
	//"time"
)

type Peers struct {
	mu    sync.RWMutex
	peers []string
	local string
}

var peers *Peers

/*
func NewPeers(kv []*mvccpb.KeyValue, local string) *Peers {
	peers := make([]string, 0)
	for _, ev := range kv {
		peers = append(peers, string(ev.Key))
	}
	return &Peers{peers: peers, local: local}
}

func (p *Peers) GetPeers() (ret []string) {
	p.mu.RLock()
	defer p.mu.RUnlock()
	for _, pv := range p.peers {
		if pv != p.local {
			ret = append(ret, pv)
		}
	}
	return ret
}

func (p *Peers) Update(event mvccpb.Event) {
	p.mu.Lock()
	defer p.mu.Unlock()
	switch event.Type {
	case mvccpb.DELETE:
		log.Info("detect change: delete")
		var newpeers []string
		for _, peer := range p.peers {
			if peer != string(event.Kv.Key) {
				newpeers = append(newpeers, peer)
			}
		}
		p.peers = newpeers
	case mvccpb.PUT:
		log.Info("detect change: put")
		p.peers = append(p.peers, string(event.Kv.Key))
	}
}

func KeepAliveAndFindPeers(port int, conf *Config) {
	timeout := 5 * time.Second
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   conf.EtcdAddr,
		DialTimeout: timeout,
	})
	if err != nil {
		log.Errorf("error when connect etcd , %v", err)
		return
	}
	defer cli.Close()
	resp, err := cli.Grant(context.TODO(), 5)
	if err != nil {
		log.Errorf("error when fetching lease from etcd , %v", err)
		return
	}
	ip, err := common.GetAddr(conf.MondoAddr)
	if err != nil {
		log.Errorf("error when fetching local address , %v", err)
		return
	}
	if port == 0 {
		log.Errorf("error when fetching local port")
		return
	}
	localAddr := fmt.Sprintf("%s:%d", ip, port)
	etcdKey := fmt.Sprintf("/golia-relay/peers/%s", localAddr)

	_, err = cli.Put(context.TODO(), etcdKey, "...", clientv3.WithLease(resp.ID))
	if err != nil {
		log.Errorf("error when adding to etcd, key: %s  %v", etcdKey, err)
		return
	}
	_, err = cli.KeepAlive(context.TODO(), resp.ID)
	if err != nil {
		log.Errorf("error when sending keepalive to etcd, key: %v", err)
		return
	}
	////
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	respx, err := cli.Get(ctx, "/golia-relay/peers/", clientv3.WithPrefix(), clientv3.WithSort(clientv3.SortByKey, clientv3.SortDescend))
	cancel()
	if err != nil {
		log.Errorf("error when fetching peers from etcd, key: %v", err)
		return
	}
	peers = NewPeers(respx.Kvs, localAddr)

	rch := cli.Watch(context.Background(), "/golia-relay/peers/", clientv3.WithPrefix())
	log.Info("init local ,watching on etcd...")
	for wresp := range rch {
		for _, ev := range wresp.Events {
			peers.Update(mvccpb.Event(*ev))
		}
	}
}
*/
